package cn.zmit.kuxi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.DTDHandler;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.binner.SliderBanner;
import cn.zmit.kuxi.adapter.MainSliderBannerOne;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.event.EventFactory;
import cn.zmit.kuxi.image.ImageDisplayer;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.PtrHeader;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

/** * @author @parameter * @return */
public class GoodsDetailActivity extends BaseActivity {
	@ViewInject(R.id.tv_current_goods_image_item)
	private TextView tv_current_goods_image_item;
	@ViewInject(R.id.tv_all_goods_image_count)
	private TextView tv_all_goods_image_count;
	@ViewInject(R.id.tv_goods_title_join)
	private TextView tv_goods_title_join;
	@ViewInject(R.id.tv_goods_detail_data)
	private TextView tv_goods_detail_data;
	@ViewInject(R.id.tv_goods_introduction)
	private TextView tv_goods_introduction;
	@ViewInject(R.id.progressBarPeople)
	private ProgressBar progressBarPeople;
	@ViewInject(R.id.tv_goods_allPeople)
	private TextView tv_goods_allPeople;
	@ViewInject(R.id.tv_goods_alreadyJoin)
	private TextView tv_goods_alreadyJoin;
	@ViewInject(R.id.imag_win_pic)
	private ImageView imag_win_pic;
	@ViewInject(R.id.tv_win_title)
	private TextView tv_win_title;
	@ViewInject(R.id.tv__win_join_num)
	private TextView tv__win_join_num;
	@ViewInject(R.id.tv_win_num)
	private TextView tv_win_num;
	@ViewInject(R.id.tv_win_time)
	private TextView tv_win_time;
	@ViewInject(R.id.rl_pic_detail)
	private RelativeLayout rl_pic_detail;
	@ViewInject(R.id.rl_pic_detail)
	private RelativeLayout rl_join_record;
	@ViewInject(R.id.rl_old_record)
	private RelativeLayout rl_old_record;
	@ViewInject(R.id.rl_old_share)
	private RelativeLayout rl_old_share;
	@ViewInject(R.id.btn_goods_nowJoin)
	private Button btn_goods_nowJoin;
	@ViewInject(R.id.btn_goods_joinCarts)
	private Button btn_goods_joinCarts;
	@ViewInject(R.id.ll_win_user)
	private LinearLayout ll_win_user;
	private String userid, gp_id, title, goodsId, allNeed, goodsName,
			description, joinCount;
	double result;
	/**
	 * 装ImageView数组
	 */
	private ImageView[] mImageViews;
	private List<String> strings;
	Boolean hasLog;

	@ViewInject(R.id.slider_banner)
	private SliderBanner sliderBanner;
	/**
	 * 轮播图控制器
	 */
	private MainSliderBannerOne mainSliderBanner;

	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleView("商品详情", true);
		setContentView(R.layout.activity_goods_details);
		ViewUtils.inject(this);
		// initView();
		// 判断是否登录
		hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			userid = PreferenceHelper.readString(context,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}

		initPtr();
	}

	/**
	 * 初始化轮播图
	 */
	private void initSliderBanner() {
		RelativeLayout.LayoutParams lyp = new RelativeLayout.LayoutParams(
				ScreenUtils.getScreenWidth(context),
				(int) (ScreenUtils.getScreenWidth(context) * 1f / 16 * 9.6f));
		sliderBanner.setLayoutParams(lyp);
		mainSliderBanner = new MainSliderBannerOne(sliderBanner);
	}

	private void getDetailData() {
		gp_id = getTextFromBundle("gp_id");
		RequestTask.getInstance().getGoodsDetail(this,
				getTextFromBundle("gp_id"), new onRequestListener());// 请求
		initSliderBanner();
		ptr_view.refreshComplete();
	}

	// 请求
	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);

			JsonData jsonData = JsonData.create(response);
			JsonData data = jsonData.optJson("info");

			JsonData data2 = jsonData.optJson("prev_winner");
			int now_time = jsonData.optInt("now_time");
			final String win_user_id = data2.optString("win_user_id");
			if (data != null && data.length() > 0) {
				joinCount = data.optString("buy_count");
				title = data.optString("phase");
				goodsId = data.optString("goods_id");
				allNeed = data.optString("price");
				goodsName = data.optString("name");
				description = data.optString("description");

				mainSliderBanner.play(data.optJson("banner"), true);

				tv_goods_introduction.setText(description);
				tv_goods_title_join.setText("第" + title + "期");

				tv_goods_detail_data.setText(goodsName);
				tv_goods_allPeople.setText("总需人数：" + allNeed);
				tv_goods_alreadyJoin.setText("已参与：" + joinCount);
				ll_win_user.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(GoodsDetailActivity.this,
								HisCenterActivity.class);
						intent.putExtra("win_id", win_user_id);
						GoodsDetailActivity.this.startActivity(intent);
					}
				});

				double all = Integer.parseInt(allNeed);
				double join = Integer.parseInt(joinCount);
				result = (join / all) * 100;
				progressBarPeople.setMax(100);
				progressBarPeople.setProgress((int) result);

				// 判断商品期数 第一期隐藏上期中奖用户，反之显示
				if (title.equals("1")) {
					ll_win_user.setVisibility(View.GONE);
				} else {
					ll_win_user.setVisibility(View.VISIBLE);
				}
			}

			if (data2 != null && data2.length() > 0) {
				String buy_count = data2.optString("buy_count");
				String phone = data2.optString("phone");
				String lucky_number = data2.optString("lucky_number");
				int old_time = data2.optInt("unix_announceOn");
				int detime = old_time - now_time;
				String buyOn = data2.optString("buyOn");
				String avatar = data2.optString("avatar");
				if (detime > 0) {
					tv_win_title.setText("获奖用户：" + "敬请期待");
					tv__win_join_num.setText("参加次数：" + "计算中...");
					tv_win_num.setText("幸运号码：" + "计算中...");
					tv_win_time.setText("参与时间：" + "计算中...");
					imag_win_pic.setImageResource(R.drawable.user_pic_def);
				} else {
					tv_win_title.setText("获奖用户：" + phone);
					tv__win_join_num.setText("参加次数：" + buy_count);
					tv_win_num.setText("幸运号码：" + lucky_number);
					tv_win_time.setText("参与时间：" + buyOn);
					if (avatar != null && avatar.length() > 0) {
						ImageDisplayer.getInstance().dispalyImageWithRadius(
								Url.IMAGR_ROOT + avatar, imag_win_pic, 0);
					} else {
						imag_win_pic.setImageResource(R.drawable.user_pic_def);
					}
				}

			}
		}

		@Override
		public void onRequestFailed(String error) {
			super.onRequestFailed(error);
		}

		@Override
		public void onRequestPrepare() {
			super.onRequestPrepare();
		}
	}

	@OnClick({ R.id.btn_goods_nowJoin, R.id.btn_goods_joinCarts,
			R.id.rl_pic_detail, R.id.rl_join_record, R.id.rl_old_share,
			R.id.rl_old_record })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.btn_goods_nowJoin:// 立即参与
			// 发送数据过去判断该商品是否已经在当前用户购物车id中
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("gp_id", getTextFromBundle("gp_id"));
			map1.put("user_id", userid);
			RequestTask.getInstance().getIsShoppingCarts(this, map1,
					new onIsShoppingCarts());

			break;
		case R.id.btn_goods_joinCarts:// 加入购物车
			if (hasLog) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_id", userid);
				map.put("gp_id", gp_id);
				map.put("number", "1");
				RequestTask.getInstance().doAddCarts(this, map,
						new onAddRequestListener());
				Toast.makeText(context, "加入成功", 0).show();
			} else {
				openActivity(LoginActivity.class);
			}

			break;
		case R.id.rl_pic_detail:// 图文详情
			Bundle bundle4 = new Bundle();
			bundle4.putString("title", title);
			bundle4.putString("goodsName", goodsName);
			bundle4.putString("allNeed", allNeed);
			bundle4.putString("joinCount", joinCount);
			bundle4.putDouble("progress", result);
			bundle4.putString("description", description);
			bundle4.putString("gp_id", gp_id);
			openActivity(ImagTextDetailsActivity.class, bundle4);
			break;
		case R.id.rl_join_record:// 参与用户
			Bundle bundle2 = new Bundle();
			bundle2.putString("gp_id", getTextFromBundle("gp_id"));
			openActivity(JoinUserActivity.class, bundle2);
			break;
		case R.id.rl_old_share:// 往期晒单
			Bundle bundle5 = new Bundle();
			bundle5.putString("goods_id", goodsId);
			openActivity(OldShareActivity.class, bundle5);
			break;
		case R.id.rl_old_record:// 往期揭晓
			if (title.equals("1")) {
				Toast.makeText(this, "该商品还未有中奖记录", 0).show();
			} else {
				Bundle bundle3 = new Bundle();
				bundle3.putString("goods_id", goodsId);
				openActivity(OldAnnouncedActivity.class, bundle3);
			}
			break;
		default:
			break;
		}

	}

	// 加入购物车请求
	private class onAddRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			String data = jsonData.optString("code");
			if (data.equals("1")) {
				int count = jsonData.optInt("my_goods_count");
				EventFactory.sendUpdateCartCount(count);
				// ToastUtils.show(context, jsonData.optString("message"));
			} else {
				// ToastUtils.show(context, jsonData.optString("message"));
			}
		}
	}

	// 判断是否加入了购物车
	private class onIsShoppingCarts extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			String code = jsonData.optString("code");
			String desc = jsonData.optString("description");
			if (code.equals("0")) {// 购物车有了
				Intent intent = new Intent(GoodsDetailActivity.this,
						HomeActivity.class);
				intent.putExtra("jump_index", 3);
				startActivity(intent);
			} else {
				Bundle bundle = new Bundle();
				bundle.putString("flag", "详情界面跳转");
				bundle.putString("title", title);
				bundle.putString("goodsName", goodsName);
				bundle.putString("allNeed", allNeed);
				bundle.putString("joinCount", joinCount);
				bundle.putDouble("progress", result);
				bundle.putString("description", description);
				bundle.putString("gp_id", getTextFromBundle("gp_id"));
				openActivity(NowJoinActivity.class, bundle);
			}
		}
	}

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {

						getDetailData();
					}

				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				// TODO Auto-generated method stub
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						content, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

}
